package com.jeesite.modules.exam.score.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.assessment.service.DcSupExamInfoService;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuota;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaAdd;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.quota.service.DcSupExamQuotaService;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaInfoService;
import com.jeesite.modules.exam.score.entity.DcSupExamScore;
import com.jeesite.modules.exam.score.entity.DcSupExamSumScore;
import com.jeesite.modules.exam.score.service.DcSupExamScoreService;
import com.jeesite.modules.exam.score.service.DcSupExamSumScoreService;
import com.jeesite.modules.exam.score.vo.DcSupExamQuotaOrgVo;
import com.jeesite.modules.exam.score.vo.DcSupExamVo;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.utils.OfficeUtil;
import com.jeesite.modules.utils.TemplateExcelUtils;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jxls.common.Context;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 考核任务评分汇总表Controller
 *
 * @author xhc
 * @version 2022-05-28
 */
@Controller
@RequestMapping(value = "${adminPath}/score/dcSupExamSumScore")
@RequiredArgsConstructor
public class DcSupExamSumScoreController extends BaseController {

    private final DcSupExamSumScoreService dcSupExamSumScoreService;

    private final DcSupExamInfoService dcSupExamInfoService;

    private final DcSupExamScoreService dcSupExamScoreService;

    private final DcSupExamQuotaService dcSupExamQuotaService;

    private final DcSupExamSumQuotaInfoService dcSupExamSumQuotaInfoService;



    /**
     * 获取数据
     */
    @ModelAttribute
    public DcSupExamSumScore get(String id, boolean isNewRecord) {
        return dcSupExamSumScoreService.get(id, isNewRecord);
    }

    /**
     * 汇总页面
     */
    @RequiresPermissions("score:dcSupExamSumScore:view")
    @RequestMapping(value = {"view", ""})
    public String view(DcSupExamInfo dcSupExamInfo,String selectExamOrg, Model model) {
        List<DcSupExamQuotaOrgVo> assessmentUnit = dcSupExamSumScoreService.findSumAssessmentUnit(dcSupExamInfo.getId(), null);
        model.addAttribute("assessmentUnit", assessmentUnit);
        model.addAttribute("selectExamOrg",selectExamOrg);
        return "modules/exam/score/dcSupExamSumScore";
    }

    /**
     * 指标汇总查看提交页面
     *
     * @param model
     * @return
     */
    @RequiresPermissions("score:dcSupExamSumScore:view")
    @RequestMapping("subView")
    public String subView(@RequestParam("examId") String examId, @RequestParam("exameOrg") String exameOrg, @RequestParam("scoreStatus") String scoreStatus,Model model) {
        List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamSumScoreService.findDcSupExamSumScore(examId, exameOrg);
        List<DcSupExamQuotaAdd> dcSupExamQuotaAdds = new ArrayList<>();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setScoreType("9");
        dcSupExamScoreVo.setExameOrg(exameOrg);
        DcSupExamScore dcSupExamScore = dcSupExamScoreService.findDcSupExamScore(dcSupExamScoreVo);//获取关键指标信息
        if (dcSupExamScore==null){
            //未评分 取quota_info 加减分指标
            dcSupExamQuotaAdds=dcSupExamSumScoreService.findDcSUpExamMinuspointsQuotaInfo(examId,exameOrg);
        }else {
            dcSupExamQuotaAdds=dcSupExamSumScoreService.findDcSupExamQuoatAdd(examId, exameOrg);
        }
        DcSupExamInfo dcSupExamInfo = dcSupExamInfoService.get(examId);
        DcSupExamVo dcSupExamVo = new DcSupExamVo();
        dcSupExamVo.setDcSupScoreList(dcSupExamSumQuotaInfos);
        dcSupExamVo.setDcSupExamQuotaAddList(dcSupExamQuotaAdds);
        dcSupExamVo.setDcSupExamInfo(dcSupExamInfo);
        dcSupExamVo.setExameOrg(exameOrg);
        dcSupExamVo.setExamId(examId);
        dcSupExamVo.setDcSupExamScore(Optional.ofNullable(dcSupExamScore).orElseGet(DcSupExamScore::new));
        dcSupExamVo.getDcSupExamScore().setScoreStatus(scoreStatus);
        model.addAttribute("dcSupExamVo", dcSupExamVo);
        return "modules/exam/score/dcSupExamSumSubScore";
    }

    @RequiresPermissions("score:dcSupExamSumScore:view")
    @RequestMapping("exportSumScore")
    public void exportSumScore(@RequestParam("examId") String examId, @RequestParam("exameOrg") String exameOrg,HttpServletResponse response) {
        List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamSumScoreService.findDcSupExamSumScore(examId, exameOrg);
        List<DcSupExamQuotaAdd> dcSupExamQuotaAdds = new ArrayList<>();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setScoreType("9");
        dcSupExamScoreVo.setExameOrg(exameOrg);
        DcSupExamScore dcSupExamScore = dcSupExamScoreService.findDcSupExamScore(dcSupExamScoreVo);//获取关键指标信息
        if (dcSupExamScore==null){
            //未评分 取quota_info 加减分指标
            dcSupExamQuotaAdds=dcSupExamSumScoreService.findDcSUpExamMinuspointsQuotaInfo(examId,exameOrg);
        }else {
            dcSupExamQuotaAdds=dcSupExamSumScoreService.findDcSupExamQuoatAdd(examId, exameOrg);
        }
        Double totalScore1 = 0d;
        Double totalWeight1 = 0d;
        Double totalScore2 = 0d;
        Double totalWeight2 = 0d;
        String examOrgName="";
        for(DcSupExamSumQuotaInfo score: dcSupExamSumQuotaInfos){
            String assessMethod = DictUtils.getDictLabel("dc_exam_assessment", score.getAssessMethod(), "未知");
            String quotaType = DictUtils.getDictLabel("dc_quotaType", score.getQuotaType(), "未知");
            score.setQuotaType(quotaType);
            score.setAssessMethod(assessMethod);
            totalScore1 = totalScore1+score.getQuotaScore();
            totalWeight1 = totalWeight1+score.getQuotaWeight();
            examOrgName=score.getExameOrgName();
        }
        for(DcSupExamQuotaAdd score: dcSupExamQuotaAdds){
            Double quotaScore = 0d;
            String assessMethod = DictUtils.getDictLabel("dc_exam_assessment", score.getAssessMethod(), "未知");
            if(StringUtils.equals(score.getQuotaClass(),"2")){
                quotaScore = score.getQuotaScore();
            }
            if(StringUtils.equals(score.getQuotaClass(),"3")){
                quotaScore = -score.getQuotaScore();
            }
            String quotaType = DictUtils.getDictLabel("dc_quotaType", score.getQuotaType(),"未知");
            score.setQuotaType(quotaType);
            score.setAssessMethod(assessMethod);
            totalScore2 = totalScore2+quotaScore;
            totalWeight2 = totalWeight2+score.getQuotaWeight();
        }

        try {
            Context context = new Context();
            Map<String,Object> param = new HashMap<>();
            context.putVar("list1",dcSupExamSumQuotaInfos);
            context.putVar("list2",dcSupExamQuotaAdds);
            context.putVar("totalWeight1",totalWeight1);
            context.putVar("totalScore1",totalScore1);
            context.putVar("totalWeight2",totalWeight2);
            context.putVar("totalScore2",totalScore2);
            context.putVar("totalScore",totalScore1+totalScore2);
            TemplateExcelUtils.downLoadExcel("评分汇总-"+examOrgName,"sumscore.xls",context,examOrgName,response);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }

    }

    /**
     * 汇总列表页面
     */
    @RequiresPermissions("score:dcSupExamSumScore:view")
    @RequestMapping("sumScoreListView")
    public String sumScoreListView(DcSupExamInfo dcSupExamInfo, Model model) {
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        model.addAttribute("dcSupExamInfo", dcSupExamInfo);
        return "modules/exam/score/dcSupExamSumScoreList";
    }


    /**
     * 查询汇总首页列表数据
     */
    @RequestMapping(value = "sumScoreListData")
    @ResponseBody
    public Page<DcSupExamInfo> listData(DcSupExamInfo dcSupExamInfo, HttpServletRequest request, HttpServletResponse response) {
        dcSupExamInfo.setPage(new Page<>(request, response));
        dcSupExamInfo.setExamStatus("2");
        return dcSupExamSumScoreService.findExamSumProgressList(dcSupExamInfo);
    }

    /**
     * 提交汇总数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:view")
    @PostMapping("/saveSumScore")
    @ResponseBody
    public String saveSumScore(DcSupExamVo dcSupExamVo) {
        if (UserUtils.getUser().getUserCode().equals("system")) {
            return renderResult(Global.FALSE,"操作禁止！");
        }
        String examId = dcSupExamVo.getDcSupExamScore().getExamId();
        // 判断单项指标和关键指标是否都提交过了
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setScoreType("2");
        dcSupExamScoreVo.setExameOrg(dcSupExamVo.getExameOrg());
        DcSupExamScore dcSupExamGJScore = dcSupExamScoreService.findDcSupExamScore(dcSupExamScoreVo);
        DcSupExamScore dcSupExamDXScore = dcSupExamSumScoreService.findDxExamScoreLimitOne(examId,dcSupExamVo.getExameOrg());
        DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo = new DcSupExamSumQuotaInfo();
        dcSupExamSumQuotaInfo.setExamId(examId);
        List<DcSupExamSumQuotaInfo> releaseDcSUpExamSumQuotaInfo = dcSupExamSumQuotaInfoService.findReleaseDcSUpExamSumQuotaInfo(dcSupExamSumQuotaInfo);
        if (dcSupExamGJScore == null) {
            long gjcount = releaseDcSUpExamSumQuotaInfo.stream().filter(x->dcSupExamVo.getExameOrg().equals(x.getExameOrg())).filter(x -> "1".equals(x.getQuotaGroup())).count();
            if (gjcount!=0){
                return renderResult(Global.FALSE, "关键指标考核未提交分数！");
            }
        }
        if (dcSupExamDXScore == null) {
            long dxcount = releaseDcSUpExamSumQuotaInfo.stream().filter(x->dcSupExamVo.getExameOrg().equals(x.getExameOrg())).filter(x -> "2".equals(x.getQuotaGroup())).count();
            if (dxcount!=0){
             return renderResult(Global.FALSE, "单项指标考核未提交分数！");
            }
        }
        dcSupExamSumScoreService.saveSumScore(dcSupExamVo);
        return renderResult(Global.TRUE, "保存成功！");
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<DcSupExamSumScore> listData(DcSupExamSumScore dcSupExamSumScore, HttpServletRequest request, HttpServletResponse response) {
        dcSupExamSumScore.setPage(new Page<>(request, response));
        Page<DcSupExamSumScore> page = dcSupExamSumScoreService.findPage(dcSupExamSumScore);
        return page;
    }


    /**
     * 保存数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated DcSupExamSumScore dcSupExamSumScore) {
        dcSupExamSumScoreService.save(dcSupExamSumScore);
        return renderResult(Global.TRUE, text("保存考核任务评分汇总表成功！"));
    }

    /**
     * 停用数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:edit")
    @RequestMapping(value = "disable")
    @ResponseBody
    public String disable(DcSupExamSumScore dcSupExamSumScore) {
        dcSupExamSumScore.setStatus(DcSupExamSumScore.STATUS_DISABLE);
        dcSupExamSumScoreService.updateStatus(dcSupExamSumScore);
        return renderResult(Global.TRUE, text("停用考核任务评分汇总表成功"));
    }

    /**
     * 启用数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:edit")
    @RequestMapping(value = "enable")
    @ResponseBody
    public String enable(DcSupExamSumScore dcSupExamSumScore) {
        dcSupExamSumScore.setStatus(DcSupExamSumScore.STATUS_NORMAL);
        dcSupExamSumScoreService.updateStatus(dcSupExamSumScore);
        return renderResult(Global.TRUE, text("启用考核任务评分汇总表成功"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("score:dcSupExamSumScore:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(DcSupExamSumScore dcSupExamSumScore) {
        dcSupExamSumScoreService.delete(dcSupExamSumScore);
        return renderResult(Global.TRUE, text("删除考核任务评分汇总表成功！"));
    }

    /**
     * 退回汇总被考核单位状态到未提交状态
     */
    @ResponseBody
    @PostMapping("withdrawSumScore")
    public String withdrawSumScore(String examId,String exameOrg){
        int update = dcSupExamSumScoreService.withdrawSumScore(examId,exameOrg);
        if(update>0){
            return renderResult(Global.TRUE, text("退回成功"));
        }
        return renderResult(Global.FALSE, text("退回失败"));
    }


}
